package cn.sdhuijin.healthexam.activity;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import cn.sdhuijin.healthexam.DatabaseHelper;
import cn.sdhuijin.healthexam.ExitApplication;
import cn.sdhuijin.healthexam.R;
import cn.sdhuijin.healthexam.bean.Item;
import cn.sdhuijin.healthexam.util.Util;

/**
 * 查询列表
 * 
 * @author sunping
 * 
 */
public class DataListActivity extends AbstractActivity implements
		OnClickListener {

	ListView lv;
	List<Item> items = new ArrayList<Item>();
	Context mContext;
	MyListAdapter adapter;
	List<Integer> listItemID = new ArrayList<Integer>();
	private DatabaseHelper dbh;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_data_list);
		ExitApplication.getInstance().addActivity(this);

		// 获取intent实例
		Intent intent = getIntent();
		// 获取传递过来的sql语句
		String searchSql = intent.getStringExtra("sql");
		mContext = getApplicationContext();
		lv = (ListView) findViewById(R.id.search_result_list);

		initItemData(searchSql);
		adapter = new MyListAdapter(items, this);
		lv.setAdapter(adapter);

		setButtonListener(this, R.id.btn_back);
	}

	/**
	 * 填充列表数据
	 */
	private void initItemData(String sql) {
		dbh = new DatabaseHelper(DataListActivity.this);
		items = dbh.searchList(sql);
	}

	// 把字符串转为日期
	public static String ConverToDate(String strDate) throws Exception {
		DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = df1.parse(strDate);
		DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df2.format(date);
	}

	// 自定义ListView适配器
	class MyListAdapter extends BaseAdapter {
		List<Boolean> mChecked;
		List<Item> listItem;
		private OnClickListener onclickListener;

		private static final int NAME_TAG = 0;
		private static final int CARDID_TAG = 1;
		private static final int SEX_TAG = 2;
		private static final int BIRTHDATE_TAG = 3;
		private static final int STYLE_TAG = 4;
		private static final int DOCTOR_TAG = 5;
		private static final int INPUTDATE_TAG = 6;

		HashMap<Integer, View> map = new HashMap<Integer, View>();
		private LayoutInflater mInflater;

		public MyListAdapter(List<Item> list, OnClickListener onclick) {
			listItem = new ArrayList<Item>();
			listItem = list;
			onclickListener = onclick;

			mChecked = new ArrayList<Boolean>();
			for (int i = 0; i < list.size(); i++) {
				mChecked.add(false);
			}
		}

		@Override
		public int getCount() {
			return listItem.size();
		}

		@Override
		public Object getItem(int position) {
			return listItem.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder;

			if (convertView == null) {
				mInflater = (LayoutInflater) mContext
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = mInflater.inflate(R.layout.activity_item, null);
				holder = new ViewHolder();
				holder.name = (TextView) convertView.findViewById(R.id.item01);
				holder.name.setTag(NAME_TAG);
				holder.cardId = (TextView) convertView
						.findViewById(R.id.item02);
				holder.name.setTag(CARDID_TAG);
				holder.sex = (TextView) convertView.findViewById(R.id.item03);
				holder.name.setTag(SEX_TAG);
				holder.birthDate = (TextView) convertView
						.findViewById(R.id.item04);
				holder.name.setTag(BIRTHDATE_TAG);
				holder.style = (TextView) convertView.findViewById(R.id.item05);
				holder.name.setTag(STYLE_TAG);
				holder.doctor = (TextView) convertView
						.findViewById(R.id.item06);
				holder.name.setTag(DOCTOR_TAG);
				holder.inputDate = (TextView) convertView
						.findViewById(R.id.item07);
				holder.name.setTag(INPUTDATE_TAG);
				holder.btModify = (Button) convertView
						.findViewById(R.id.btn_modify);
				holder.btDelete = (Button) convertView
						.findViewById(R.id.btn_delete);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.name.setText(listItem.get(position).getName());
			holder.name.setTextColor(android.graphics.Color.RED);
			holder.cardId.setText(listItem.get(position).getCardId());
			holder.sex.setText(listItem.get(position).getSex());
			holder.birthDate.setText((CharSequence) listItem.get(position)
					.getBirthDate());
			holder.style.setText(listItem.get(position).getStyle());
			holder.inputDate.setText(Util.formatDateTime(listItem.get(position)
					.getInputDate()));
			holder.doctor.setText(listItem.get(position).getDoctor());

			// if (!listItem.get(position).getStyle().equals("档案")) {
			// holder.btModify.setVisibility(View.INVISIBLE);
			// } else {
			holder.btModify.setVisibility(View.VISIBLE);
			// }
			holder.btDelete.setTag(String.valueOf(position));

			holder.name.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					String fileName = listItem.get(position).getInputDate();
					boolean fileExist = checkFileExist(fileName);
					if (fileExist) {
						String dataType = listItem.get(position).getStyle();
						startActivityByDataType(dataType, fileName);
					} else {
						DataListActivity.this
								.toastInformation(R.string.record_deleted);
					}
				}
			});
			holder.btModify.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					String fileName = listItem.get(position).getInputDate();
					boolean fileExist = checkFileExist(fileName);
					if (fileExist) {
						String dataType = listItem.get(position).getStyle();
						startEditActivityByDataType(dataType, fileName);
					} else {
						DataListActivity.this
								.toastInformation(R.string.record_deleted);
					}
				}
			});

			holder.btDelete.setOnClickListener(onclickListener);
			return convertView;
		}
	}

	private boolean checkFileExist(String fileName) {
		File file = null;
		boolean exist = false;
		try {
			file = new File(Environment.getExternalStorageDirectory().getPath()
					+ "/health/" + fileName + ".txt");
			if (file.exists()) {
				exist = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return exist;
	}

	/**
	 * 通过不同数据类型启动不同Activity
	 * 
	 * @param dataType
	 *            数据类型
	 * @param fileName
	 *            文件名称
	 */
	private void startActivityByDataType(String dataType, String fileName) {
		Intent intent = new Intent();
		intent.putExtra("filename", fileName);
		if ("档案".equals(dataType)) {
			intent.setClass(DataListActivity.this, ArchivesInfoActivity.class);
		} else if ("体检".equals(dataType)) {
			intent.setClass(DataListActivity.this, HealthExamInfoActivity.class);
		} else if ("精神病随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					MentalVisitInfoActivity.class);
		} else if ("高血压随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					HypertensionVisitInfoActivity.class);
		} else if ("糖尿病随访".equals(dataType)) {
			intent.setClass(DataListActivity.this, DiabetesInfoActivity.class);
		} else if ("中医体质判定".equals(dataType)) {
			intent.setClass(DataListActivity.this, BodyJudgeInfoActivity.class);
		} else if ("产前第一次随访".equals(dataType)) {
			intent.setClass(DataListActivity.this, ChanQianInfoActivity.class);
		} else if ("产前第二次随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					SecondChanQianInfoActivity.class);
		} else if ("产前第三次随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ThirdChanQianInfoActivity.class);
		} else if ("产前第四次随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ForthChanQianInfoActivity.class);
		} else if ("产前第五次随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					FifthChanQianInfoActivity.class);
		} else if ("产后随访".equals(dataType)) {
			intent.setClass(DataListActivity.this, ChanHouInfoActivity.class);
		} else if ("产后四十二天随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ChanHouSiShiErInfoActivity.class);
		} else if ("新生儿随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					NewChildrenVisitInfoActivity.class);
		} else if ("新生儿满月随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ManYueVisitInfoActivity.class);
		} else if ("新生儿三月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					SanYueVisitInfoActivity.class);
		} else if ("新生儿六月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					LiuYueVisitInfoActivity.class);
		} else if ("新生儿八月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this, BaYueVisitInfoActivity.class);
		} else if ("新生儿十二月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ShiErYueVisitInfoActivity.class);
		} else if ("新生儿十八月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ShiBaYueVisitInfoActivity.class);
		} else if ("新生儿二十四月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ErShiSiYueVisitInfoActivity.class);
		} else if ("新生儿三十月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					SanShiYueVisitInfoActivity.class);
		} else if ("新生儿三岁龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					SanSuiVisitInfoActivity.class);
		} else if ("新生儿四岁龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this, SiSuiVisitInfoActivity.class);
		} else if ("新生儿五岁龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this, WuSuiVisitInfoActivity.class);
		} else if ("新生儿六岁龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					LiuSuiVisitInfoActivity.class);
		}
		startActivity(intent);
	}

	/**
	 * 通过不同数据类型启动不同Activity
	 * 
	 * @param dataType
	 *            数据类型
	 * @param fileName
	 *            文件名称
	 */
	private void startEditActivityByDataType(String dataType, String fileName) {
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putString("createDate", fileName);
		intent.putExtra("bundle", bundle);
		if ("档案".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					EditPersonDocFirstActivity.class);
		} else if ("体检".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					HealthExamFirstActivity.class);
		} else if ("精神病随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					EditVisitMentalFirstActivity.class);
		} else if ("高血压随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					EditVisitHypertensionFirstActivity.class);
		} else if ("糖尿病随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					EditVisitDiabetesFirstActivity.class);
		} else if ("中医体质判定".equals(dataType)) {
			DataListActivity.this
					.toastInformation(R.string.function_not_complete);
			return;
		} else if ("产前第一次随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ChanQianVisitFirstActivity.class);
		} else if ("产前第二次随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ChanQianSecondVisitFirstActivity.class);
		} else if ("产前第三次随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ChanQianThirdVisitFirstActivity.class);
		} else if ("产前第四次随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ChanQianForthVisitFirstActivity.class);
		} else if ("产前第五次随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ChanQianFifthVisitFirstActivity.class);
		} else if ("产后随访".equals(dataType)) {
			intent.setClass(DataListActivity.this, ChanHouVisitActivity.class);
		} else if ("产后四十二天随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ChanHouSiShiErVisitActivity.class);
		} else if ("新生儿随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					NewChildrenVisitFirstActivity.class);
		} else if ("新生儿满月随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ManYueVisitFirstActivity.class);
		} else if ("新生儿三月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					SanYueVisitFirstActivity.class);
		} else if ("新生儿六月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					LiuYueVisitFirstActivity.class);
		} else if ("新生儿八月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					BaYueVisitFirstActivity.class);
		} else if ("新生儿十二月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ShiErYueVisitFirstActivity.class);
		} else if ("新生儿十八月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ShiBaYueVisitFirstActivity.class);
		} else if ("新生儿二十四月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					ErShiSiYueVisitFirstActivity.class);
		} else if ("新生儿三十月龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					SanShiYueVisitFirstActivity.class);
		} else if ("新生儿三岁龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					SanSuiVisitFirstActivity.class);
		} else if ("新生儿四岁龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					SiSuiVisitFirstActivity.class);
		} else if ("新生儿五岁龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					WuSuiVisitFirstActivity.class);
		} else if ("新生儿六岁龄随访".equals(dataType)) {
			intent.setClass(DataListActivity.this,
					LiuSuiVisitFirstActivity.class);
		}
		startActivity(intent);
	}

	static class ViewHolder {
		TextView name;
		TextView cardId;
		TextView sex;
		TextView birthDate;
		TextView style;
		TextView inputDate;
		TextView doctor;
		Button btModify;
		Button btDelete;
	}

	@Override
	public void onClick(final View v) {
		int clickId = v.getId();
		switch (clickId) {
		case R.id.btn_delete:
			new AlertDialog.Builder(this)
					.setTitle("提示")
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setMessage("确定删除?")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									int deleteIndex = Integer.parseInt(v
											.getTag().toString());
									dbh.deleteIndex(((Item) adapter
											.getItem(deleteIndex))
											.getInputDate());
									items.remove(deleteIndex);
									adapter.notifyDataSetChanged();
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
								}
							}).show();
			break;
		case R.id.btn_back:
			this.finish();
			break;
		default:
			break;
		}

	}
}
